// 注册页面
import React from 'react'
import Layout from './Layout'
import { Form, Input, Button, Spin, Result  } from 'antd';
import { register, register_reset } from '../../store/actions/register'
// useDispatch 触发action   useSelector获取状态
import { useDispatch, useSelector } from 'react-redux'
import { useEffect } from 'react'
import { Link } from 'react-router-dom'

function Register() {
	const dispatch = useDispatch()
	const [form] = Form.useForm() 
	// 提交
	const onFinish = (value) => {
		// 将数据传递给action为register的方法,进行reducer处理,再将状态传给store
		dispatch(register(value))
	}
	// 获取 存储在 store 里的  register 数据
	const { loading, loaded, success, message } =  useSelector(
		state => state.register
	)

	// 1.当前loading为true时,代表正在请求数据,为了提高用户体验,可以添加Spin 加载中
	const registerLoading = () => {
		if (loading) {
			return (
				<Spin />
			)
		}
	}

	// 注册成功,清除表单
	useEffect(() => {
		if (loaded && success) form.resetFields()		
	},[loaded,success]) // eslint-disable-line react-hooks/exhaustive-deps
	//  上面的代码解决React Hook useEffect has a missing dependency的问题

	// 注册成功
	const registerSuccess = () => {
		if (loaded && success) {
			return (
				<Result
					status="success"
    			title="注册成功"
					extra={
						<Button type="primary">
							<Link to="/login">登录</Link>
						</Button>
					}
				/>
			)
		}
	}

	// 注册失败 显示失败信息
	const registerFail = () => {
		if (loaded && !success) {
			return (
				<Result
					status="warning"
    			title="注册失败"
					subTitle={message} 
				/>
			)
		}
	}

	// 退出页面, 重置注册状态
	useEffect(() => {
		return () => {
			dispatch(register_reset())
		}
	}, [])  // eslint-disable-line react-hooks/exhaustive-deps

	// 注册表单组件
	const registerFrom = () => {
		return (
			<Form
				form={form}
				name="register"
				initialValues={{ remember: true }}
				onFinish={onFinish}
			>
				<Form.Item
					label="昵称"
					name="name"
					rules={[{ required: true, message: '请输入你的昵称!' }]}
				>
					<Input />
				</Form.Item> 
				<Form.Item
					label="邮箱"
					name="email"
					rules={[{ required: true, type: 'email', message: '请输入正确邮箱格式!' }]}
				>
					<Input />
				</Form.Item> 
				<Form.Item
					label="密码"
					name="password"
					rules={[{ required: true, message: '请正确输入你的密码!', min:6, max:18 }]}
				>
					<Input.Password />
				</Form.Item>
				<Form.Item>
					<Button type="primary" htmlType="submit">
						注册
					</Button>
				</Form.Item>
			</Form>
		) 
			
	}

	return (
		<>
			<Layout title="注册">
				{registerLoading()}
				{registerSuccess()}
				{registerFail()}
				{registerFrom()}
			</Layout>
		</>
	)
}

export default Register
